import 'dart:math';

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';

import 'info_button.dart';

class BigIntTest extends StatefulWidget {
  const BigIntTest({super.key});

  @override
  State<BigIntTest> createState() => _BigIntTestState();
}

class _BigIntTestState extends State<BigIntTest> {
  Database? _database;
  String? _openDbResult;
  String? _createTableResult;
  String? _insertResult;
  String? _queryResult;
  String? _updateResult;
  String? _updateResultByRaw;
  String? _updateResultByRaw1;
  String? _deleteResult;
  String? _deleteResult1;
  final String _tableName = "users";
  late String _dbName;

  void _openDB() async {
    try {
      _database = await openDatabase(
        _dbName,
        onCreate: (db, version) async {
          await db.execute("CREATE TABLE $_tableName(id INTEGER PRIMARY KEY, name TEXT, age INTEGER, create_t UNLIMITED INT)");
        },
        version: 1,
      );
      final path = await getDatabasesPath();
      setState(() {
        _openDbResult = "打开数据成功：$path";
      });
    } catch (error) {
      setState(() {
        _openDbResult = error.toString();
      });
    }
  }

  @override
  void initState() {
    _dbName = "${Random().nextInt(36000)}.db";
    _openDB();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("BigIntTest"),
      ),
      body: ListView(
        children: [
          //数据库打开状态
          Text(_openDbResult ?? '数据库未打开'),
          const SizedBox(height: 10),

          //插入数据
          _insertDataWidget(),

          //查询数据
          _queryWidget(),
        ],
      ),
    );
  }

  ///插入数据
  Widget _insertDataWidget() {
    return InfoButton(
      title: "插入数据",
      info: _insertResult,
      onTap: () async {
        if (_database != null) {
          try {
            //获取当前时间戳
            int now = DateTime.now().millisecondsSinceEpoch;
            //插入数据
            final Map<String, dynamic> data = {
              'name': 'Jack',
              'age': Random().nextInt(30000),
              'create_t': now,
            };
            final id = await _database!.insert(_tableName, data);
            setState(() {
              _insertResult = "插入数据成功：id=$id";
            });
          } catch (error) {
            setState(() {
              _insertResult = error.toString();
            });
          }
        }
      },
    );
  }

  ///查询数据
  Widget _queryWidget() {
    return InfoButton(
      title: "查询数据",
      info: _queryResult,
      onTap: () async {
        if (_database != null) {
          final maps = await _database!.query(_tableName);
          setState(() {
            _queryResult = maps.map((map) => map.toString()).join("\n");
          });
        }
      },
    );
  }
}
